## -*- coding: utf-8 -*-

#   Copyright (C) 2007, 2008 Yves Junqueira (yves@cetico.org) 
#
#    This file is part of GeekDNS.
#
#    GeekDNS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    GeekDNS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with GeekDNS.  If not, see <http://www.gnu.org/licenses/>.

"""
Implementa funções do painel de controle. Inclui todas as funções
cujo acesso deva ser restrito ao proprietario do respectivo
VPS.
"""
import logging
import turbogears
from turbogears import controllers, expose, redirect
from turbogears import identity, config, validate, error_handler
from turbogears import widgets, flash
from model import *
from geekroot.stdvars import real
from geekroot import billing, rimu
from dns import DNSPanel

log = logging.getLogger("geekroot.painel")
tabber = widgets.Tabber()

class SecurePanel(controllers.Controller):
  dns = DNSPanel()

  @expose(template=".templates.painel")
  @identity.require(identity.not_anonymous())
  def index(self):
    return dict()

  @expose(template=".templates.snmp")
  @identity.require(identity.not_anonymous())
  def snmp(self):
    return dict()

  @expose(template=".templates.vps")
  @identity.require(identity.not_anonymous())
  def vps(self):
    servers = \
    Server.select(AND(Server.q.ownerID==turbogears.identity.current.user.id,Server.q.active==True))
    return dict(servers=servers, tabber=tabber)

  @expose("json")
  @identity.require(identity.not_anonymous())
  def status(self, domain):
    myserver = Server.select(AND(
      Server.q.domain==domain,
      Server.q.ownerID==identity.current.user.id,
      Server.q.active==True,
      Server.q.rimuid!=None,
      ))[0]
    rc=rimu.RimuControl()
    vpsinfo= rc.vpsinfo(myserver.rimuid)
    # "traducao" dos resultados enviados pela rimu
    # o valor é uma tupla contendo a ordem e
    # a string a ser mostrada
    newmap = {
      'PRIMARYIP' : (0, u'IP Primário'),
      'PINGSOK': (1, u'Respondendo ping?'),
      'ISBACKUPRUNNING' : (2, u'Backup rodando agora?'),
      'ISRUNNING' : (3, u'VPS rodando?'),
      'HOSTLOAD1M': (4, u'Carga média do host (1m)'),
      'HOSTLOAD5M': (5, u'Carga média do host (5m)'),
      'HOSTLOAD15M': (6, u'Carga média do host (15m)'),
      'CURRENTMONTHDATATRANSFERMB' : (7, u'MB transferidos no mês atual'),
      'LASTMONTHDATATRANSFERMB' : (8, u'MB transferidos no mês anterior'),
      'DATATRANSFERALLOWANCEGB' : (9, u'Permissão de transferência mensal, em GB')
      #'DOMAINNAME' : 'vps1.yourbase.com.br'
      # no futuro talvez retornar host164.yourbase.com.br
      #* HOSTSERVER: host164.rimuhosting.com
      #* DATACENTER: Dallas (TX)
      #* MONTHLYRECURRINGFEE: 0.0
      #* CANCELDATE: 
    }
    yourbase_info = []
    # vpsinfo is actually a list of tuples, but we can treat it
    # like a dict in this case
    # btw, this would be a good place to use a map instead
    for (key, value) in vpsinfo:
      if newmap.has_key(key):
        if value == 'Y':
          value = 'Sim'
        elif value == 'N':
          value = u'Não'
        translation = newmap[key]
        yourbase_info.append((translation[1], value))
      
    return dict(vpsinfo=yourbase_info)

  @expose()
  @identity.require(identity.not_anonymous())
  def reboot(self, domain):
    """Reboota um servidor VPS utilizando RimuControl
    """
    myserver = Server.select(AND(
      Server.q.domain==domain,
      Server.q.ownerID==identity.current.user.id,
      Server.q.active==True,
      Server.q.rimuid!=None,
      ))[0]
    rc=rimu.RimuControl()
    try:
      rc.reboot(myserver.rimuid)
    except:
      flash("Ocorreu um erro ao iniciar o servidor.\
 Tente novamente ou entre em contato com o suporte")
    else:
      flash("O servidor será reiniciado dentro de alguns instantes")
    raise turbogears.redirect(turbogears.url('/painel'))
      
  @expose(template=".templates.pagamento")
  @identity.require(identity.not_anonymous())
  def pagamento(self, server=None):
    """Mostra links e detalhes de faturas pendentes.
    
    Com "server" definido, provavelmente este servidor
    está sendo criado agora.
    Caso contrário, cliente prov está vindo do painel.
    
    Não insere nada no banco, apenas mostra pagamento  
    """
    if server:
      myserver = Server.byDomain(server)
      pend_invoices = ServerInvoice.select(AND(
        Server.q.id==ServerInvoice.q.serverID,
        ServerInvoice.q.serverID==myserver.id,
        ServerInvoice.q.paid==False,
        Server.q.ownerID==identity.current.user.id
        ))
    else:
      pend_invoices = ServerInvoice.select(AND(
        Server.q.id==ServerInvoice.q.serverID,
        Server.q.ownerID==identity.current.user.id,
        ServerInvoice.q.paid==False
        ))
    for i in pend_invoices:
      log.debug("Pending invoice: %s" % i.server.domain)
    return dict(pend_invoices=pend_invoices)

